package io.jft.doll.tcp.handle

import com.g.base.help.d
import io.jft.doll.tcp.TcpC
import io.jft.doll.tcp.TcpC.Companion.HEAD_LENGTH
import io.jft.doll.tcp.TcpC.Companion.PROTOCOL_HEADER
import io.jft.doll.tcp.event.TcpData
import io.jft.doll.tcp.utils.BytesUtil
import io.jft.doll.tcp.utils.CRC16
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder

/**
 * Created by G on 2017/12/25 0025.
 */
class EncoderHandle : MessageToByteEncoder<TcpData>() {
    override fun encode(ctx: ChannelHandlerContext, msg: TcpData, out: ByteBuf) {
        val bodyLength = msg.data.readableBytes()
        out.writeInt(PROTOCOL_HEADER.toInt())
        out.writeShort(bodyLength)
        out.writeShort(msg.command.toInt())
        out.writeShort(CRC16.crcCal(msg.data, 0, bodyLength))
        out.writeShort(0)
        out.writeBytes(msg.data)

        d("tcp  write Header ${TcpC.comToString(msg.command)}  data ${BytesUtil.bytesToHexString(out.array().sliceArray(IntRange(HEAD_LENGTH, HEAD_LENGTH + bodyLength)), bodyLength)}")
    }
}